import React, { Component } from 'react';
import { StyleSheet, Clipboard ,PermissionsAndroid, TextInput} from 'react-native';
import { Container, Content, View, Button, Text, Toast} from 'native-base';
import { Image, Slider } from 'react-native-elements'
import { connect } from 'react-redux';

import QRCode from 'react-native-qrcode-svg';
import ImagePicker from 'react-native-image-picker';

import CameraRoll from "@react-native-community/cameraroll";
import { captureRef } from 'react-native-view-shot';
import { Header } from '../../component';
import { Colors, Metrics } from '../../theme';

class Qrcode extends Component {
  constructor(props) {
    super(props);
    this.state = {
      qrInputUri: '',
      qrCodeUri: '',
      logoBaseUri: null,
      size: 200,
      color: 'black',
      backgroundColor: 'white',
      logoSize: 40
    }
  }

  UNSAFE_componentWillMount() {

  }

  componentDidMount() {

  }

  // 点击复制
  clipboardFunc(str) {
    str = str + '';
    Clipboard.setString(str);
    Toast.show({
      text: '文本已复制!',
      type: "success"
    })
  }

  // 生成二维码
  getQrcodeFunc() {
    this.setState({ qrCodeUri: this.state.qrInputUri })
  }

  // 保存图片
  async onPressSaveFunc() {
    if (Platform.OS === 'android') {
        try {
            const granted = await PermissionsAndroid.request(
              PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
              {
                title: '申请存储权限！',
                message:
                  '申请存储权限，保存图片到相册！',
              },
            );
          } catch (err) {
            console.warn(err);
          }
    }

    if (!this.refs.saveViewShot) return;
    
    captureRef(
        this.refs.saveViewShot, {
        format: 'jpg',
        quality: 1,
        result: "tmpfile"
    })
    .then(response => {
        let imagePath = response;
        var promise = CameraRoll.save(imagePath)
        promise.then(function(result) {
            Toast.show({
                text: '图片已保存至相册!',
                type: "success"
            })
        }).catch(function(error) {
            Toast.show({
                text: '图片保存失败!',
                type: "warning"
            })
        })

    })
    .catch(e => {
        console.log(e);
    });
}

  // 选择图片
  selectPicFunc() {
    const options = {
			title: '选择图片', 
			cancelButtonTitle: '取消',
			takePhotoButtonTitle: Platform.OS === 'ios' ? '拍照' : null,
			chooseFromLibraryButtonTitle: '图片库',
			cameraType: 'back',
			mediaType: 'photo',
			videoQuality: 'high', 
			durationLimit: 10,
			maxWidth: 600,
			maxHeight: 600,
			aspectX: 2, 
			aspectY: 1,
			quality: 0.8,
			angle: 0,
			allowsEditing: false,
			noData: false,
			storageOptions: { 
				skipBackup: true, 
				path: 'images'
			},
		};
    ImagePicker.showImagePicker(options, (response) => {
      if (response.didCancel) {
        console.log('用户取消了选择图片');
      } else if (response.error) {
        console.log('ImagePicker 错误: ', response.error);
      } else {
        // response.uri
        this.setState({logoBaseUri: 'data:image/jpeg;base64,' + response.data})
      }
    });
  }

  render() {
    return (
      <Container>
        <Header title="生成二维码" onLeftPress={() => this.props.navigation.goBack()} />
        <Content>
          <TextInput
            placeholder='请输入地址'
            value={this.state.qrInputUri}
            onChangeText={(value) => this.setState({ qrInputUri: value })}
          />

          <Button onPress={() => this.selectPicFunc()}>
            <Text>添加logo</Text>
          </Button>

          {/* <View style={Styles.qrcodeCont}>
            {
              this.state.logoBaseUri ?
              <Image
                source={{ uri: this.state.logoBaseUri }}
                style={{ width: 100, height: 100 }}
              />
                :
                <Text></Text>
            }
          </View> */}

          <Slider
            value={this.state.size}
            maximumValue={300}
            onValueChange={value => this.setState({ size: value })}
          />
          <Text>二维码大小: {this.state.size}</Text>

          <Slider
            value={this.state.logoSize}
            maximumValue={100}
            onValueChange={value => this.setState({ logoSize: value })}
          />
          <Text>logo大小: {this.state.logoSize}</Text>

          <Button onPress={() => this.getQrcodeFunc()}>
            <Text>生成二维码</Text>
          </Button>

          <View style={Styles.qrcodeCont} ref="saveViewShot">
            {
              this.state.qrCodeUri ?
                <QRCode
                  value={this.state.qrCodeUri}
                  size={this.state.size}
                  logo={this.state.logoBaseUri}
                  logoSize={this.state.logoSize}
                  logoBorderRadius={1}
                  logoBackgroundColor='transparent'
                />
                :
                <Text></Text>
            }
          </View>

          {
              this.state.qrCodeUri ?
              <Button onPress={() => this.onPressSaveFunc()}>
                <Text>保存二维码</Text>
              </Button>
                :
                <Text></Text>
            }

        </Content>
      </Container>
    );
  }

}

const mapStateToProps = state => ({

});

const mapDispatchToProps = dispatch => ({

});
export default connect(mapStateToProps, mapDispatchToProps)(Qrcode);

const Styles = StyleSheet.create({
  qrcodeCont: {
    backgroundColor: '#fff',
    marginTop: 10,
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    padding: 20
  }
});